import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/chat_list_controller.dart';
import '../models/chat_model.dart';
import '../utils/avatar_util.dart';

class ChatListPage extends StatelessWidget {
  final String title;

  const ChatListPage({Key? key, required this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 使用Get.put()实例化控制器，使其在整个应用程序中可用
    final ChatListController controller = Get.put(ChatListController());

    return Scaffold(
      backgroundColor: const Color(0xFFFAFAFA),
      appBar: PreferredSize(
        preferredSize: const Size.fromHeight(56),
        child: Container(
          color: Colors.white,
          child: SafeArea(
            child: AppBar(
              backgroundColor: Colors.white,
              elevation: 0,
              title: Text(
                title,
                style: const TextStyle(
                  color: Colors.black,
                  fontWeight: FontWeight.bold,
                ),
              ),
              centerTitle: true,
            ),
          ),
        ),
      ),
      body: Column(
        children: [
          // 搜索栏
          Container(
            color: Colors.white,
            padding:
                const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
            child: GestureDetector(
              onTap: () {
                // 跳转到搜索页面
                Get.toNamed('/search');
              },
              child: Container(
                height: 36,
                decoration: BoxDecoration(
                  color: const Color(0xFFF5F5F5),
                  borderRadius: BorderRadius.circular(6),
                ),
                child: Row(
                  children: [
                    const SizedBox(width: 12),
                    Icon(Icons.search, color: Colors.grey[600], size: 18),
                    const SizedBox(width: 8),
                    Text(
                      '搜索',
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          // 聊天列表
          Expanded(
            child: Obx(
              () => ListView.separated(
                itemCount: controller.chatList.length,
                separatorBuilder: (context, index) => const Divider(
                  height: 1,
                  indent: 72,
                  color: Color(0xFFEEEEEE),
                ),
                itemBuilder: (context, index) {
                  final chat = controller.chatList[index];
                  return _buildChatItem(chat, context);
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建聊天项
  Widget _buildChatItem(ChatModel chat, BuildContext context) {
    return ListTile(
      leading: _buildAvatar(chat),
      title: Text(
        chat.name,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w500,
          color: Colors.black87,
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Text(
        chat.lastMessage,
        style: TextStyle(
          fontSize: 14,
          color: Colors.grey[600],
        ),
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      trailing: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            chat.time,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[500],
            ),
          ),
          const SizedBox(height: 4),
          if (chat.hasUnread)
            chat.unreadCount != null
                ? Container(
                    padding: const EdgeInsets.all(4),
                    decoration: const BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                    ),
                    child: Text(
                      chat.unreadCount! > 99 ? '99+' : '${chat.unreadCount}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                      ),
                    ),
                  )
                : Container(
                    width: 10,
                    height: 10,
                    decoration: const BoxDecoration(
                      color: Colors.red,
                      shape: BoxShape.circle,
                    ),
                  ),
        ],
      ),
      onTap: () => Get.find<ChatListController>().toChat(chat.id),
    );
  }

  // 构建头像
  Widget _buildAvatar(ChatModel chat) {
    // 如果有头像，则显示头像，否则显示默认头像
    if (chat.avatar != null) {
      return Container(
        width: 48,
        height: 48,
        decoration: BoxDecoration(
          color: Colors.grey[300],
          borderRadius: BorderRadius.circular(8),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Image.asset(
            chat.avatar!,
            width: 48,
            height: 48,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              // 如果加载头像失败，则显示默认头像
              return _buildDefaultAvatar(chat.name);
            },
          ),
        ),
      );
    } else {
      return _buildDefaultAvatar(chat.name);
    }
  }

  // 构建默认头像
  Widget _buildDefaultAvatar(String name) {
    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        color: Colors.grey[800],
        borderRadius: BorderRadius.circular(8),
      ),
      child: Center(
        child: Text(
          AvatarUtil.getInitials(name),
          style: const TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }
}
